<template>
	<view class="main-content">
		<MHeader>{{state.pageName}}</MHeader>
		<scroll-view scroll-y="true" style="height:calc(100% - 180rpx)">
			<!-- 业务经理 -->
			<view>
				<item name="养殖批次" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BreedingBatchName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataOne','F_QUQY_BreedingBatch','FNUMBER','F_QUQY_BreedingBatchName','FNumber','FName')" />
				</item>
				<item name="组织" sign must>
					<!-- F_QUQY_OrgId F_QUQY_ORGNAME -->
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_OrgIdName" disabled placeholder="请选择" @click.native="choose('ORG_Organizations','F_QUQY_OrgId','FNumber','F_QUQY_OrgIdName','FNumber','FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_OrgIdName" disabled placeholder="养殖批次自动带出" />
				</item>
				<item name="申请日期" must sign>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Date"  @click="chooseT('F_QUQY_Date')" placeholder="请选择" />
				</item>
				<item name="业务员">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_SalemanName" disabled placeholder="养殖批次自动带出" />
				</item>
				<item name="饲料供应商" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_FeedSupplierName"  placeholder="请选择" @click.native="choose('BD_Supplier','F_QUQY_FeedSupplier','FNUMBER','F_QUQY_FeedSupplierName','FNumber','FName','102814,109470,109471')" />
				</item>
				<item name="申请司机" sign must>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_ApplyDriverName" disabled placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo','F_QUQY_ApplyDriver','FNUMBER','F_QUQY_ApplyDriverName','FNumber','FName',null,['F_QUQY_ApplyDriverTEM','F_QUQY_CarNumber'])" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ApplyDriverName" disabled placeholder="自动带出" />
				</item>
				<!-- 			<item name="车牌号">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ApplyDriverTEM" disabled placeholder="自动带出" />
				</item> -->
				<item name="联系电话">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Phone" type="number" placeholder="请输入" />
				</item>
				<item name="地址">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_CustAddress" placeholder="请输入" />
				</item>
				<item name="拉料司机" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_PullingDriver1Name"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo','F_QUQY_PullingDriver1','FNUMBER','F_QUQY_PullingDriver1Name','FNumber','FName',null,['F_QUQY_ApplyDriver1TEM','F_QUQY_CarNumber'])" />
				</item>
				<item name="是否退货">
					<van-switch v-model="state.info.Data.Model.F_QUQY_ReturnOrNot" size="24"></van-switch>
				</item>
				<item name="备注">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Remarks" placeholder="请输入" />
				</item>
			</view>
			<!-- 待- -->
			<MHeader hidTag>
				<van-icon name="cluster" color="#1989fa" style="margin-right: 10rpx;" />饲料列表
				<template #right>
					<van-icon name="add-o" size="20" @click="appendItem" />
				</template>
			</MHeader>
			<view style="padding-bottom: 10rpx;">
				<view class="card" v-for="(item,index) in state.info.Data.Model.F_QUQY_Entity">
					<view class="card-index">{{index+1}}</view>
					<item name="饲料" sign must @longpress="longpress(item,index)">
						<input class="input" v-model="item.F_QUQY_FeedName"  placeholder="请选择" @click.native="choose('BD_MATERIAL','F_QUQY_Feed','FNUMBER','F_QUQY_FeedName','FNumber','FName',101190,null,item)" />
					</item>
					<item name="申请单位" sign>
						<input class="input" v-model="item.F_QUQY_ApplyUnitName" disabled placeholder="自动带出" />
					</item>
					<van-field v-model="item.F_RSUS_ApplyQty" type="number" label="申请数量(袋)" placeholder="请输入" @update:model-value="qtyChange(item)" input-align="right"/>
					<!-- <item name="申请数量(袋)" must>
						<input class="input" v-model="item.F_RSUS_ApplyQty" type="number" step="0.01" placeholder="请输入" @input="qtyChange(item,$event)" />
					</item> -->
					<item name="单价">
						<input class="input" v-model="item.F_QUQY_UnitPrice" type="number" placeholder="自动带出" disabled @input="priceChange(item,$event)" />
					</item>
					<item name="金额">
						<input class="input" v-model="item.F_QUQY_Amount" type="number" placeholder="自动计算" disabled />
					</item>
				</view>
			</view>
		</scroll-view>
		<view class="btns">
			<van-button type="primary" size="small" @click="save">保 存</van-button>
		</view>
	</view>
	<ChooseTime ref="chooseTime" />
	<Loading v-if="state.loading" />
</template>

<script setup>
	// 同上苗计划
	// QUQY_FeedApplication
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm, msg } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import { confirm } from '/utils/utils.js'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		loading: true,
		info: {
			FormId: 'QUQY_FeedApplication',
			Data: {
				Model: {
					// FBillNo: '',
					// FDocumentStatus: 'A', // 单据状态
					F_QUQY_OrgId: {
						FNumber: null
					},
					F_QUQY_Saleman: {
						FSTAFFNUMBER: null
					},
					F_QUQY_BreedingBatch: {
						FNUMBER: null
					},
					F_QUQY_ApplyDriver: {
						FNUMBER: null
					},
					F_QUQY_PullingDriver1: {
						FNUMBER: null
					},
					F_QUQY_FeedSupplier: {
						FNUMBER: null
					},
					F_QUQY_Date:null,
					F_QUQY_ApplyDriverName:null,
					F_QUQY_PullingDriver1Name:null,
					F_QUQY_BreedingBatchName:null,
					F_QUQY_SalemanName:null,
					F_QUQY_CustAddress:null,
					F_QUQY_Phone:null,
					F_QUQY_OrgIdName:null,
					F_QUQY_FeedSupplierName:null,
					F_QUQY_Remarks:null,
					F_QUQY_ReturnOrNot:null,
					F_QUQY_Entity: []
				}
			}
		},
		rules: {
			F_QUQY_OrgIdName: '请选择组织！',
			F_QUQY_Date: '请选择申请日期！',
			F_QUQY_BreedingBatchName: '请选择养殖批次！',
			F_QUQY_FeedSupplierName: '请选择饲料供应商！',
			F_QUQY_ApplyDriverName: '请选择申请司机！',
			F_QUQY_PullingDriver1Name: '请选择拉料司机！'
		},
		pageName: "饲料申请",
		userInfo: {},
		curOrgId: null,
		curPrice: null,
		// 饲料供应商
		GYSOrgId: null,
		materialList:[],
		F_QUQY_IsMarket:0
	})

	const qtyChange = (row) => {
		if (row.F_QUQY_UnitPrice) {
			row.F_QUQY_Amount = [(row.F_QUQY_UnitPrice *100) * (row.F_RSUS_ApplyQty*100)] / 10000
		}
	}

	const priceChange = (row, e) => {
		if (row.F_RSUS_ApplyQty) {
			row.F_QUQY_Amount = [(row.F_RSUS_ApplyQty*100) * (e.detail.value*100)] / 10000
		}
	}

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName)
	}

	// 1.组织控制（使用组织为当前选择的组织）：养殖批次
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther, row) => {
		// 🐟 1
		let mustHasOrg = ['F_QUQY_FeedSupplier', 'F_QUQY_Feed']
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_OrgIdName) return msg('请先选择养殖批次！')
		}
		
		// 选择饲料需要先选择饲料供应商
		if(Field == 'F_QUQY_Feed' && !state.info.Data.Model.F_QUQY_FeedSupplierName) {
			return msg('请先选择饲料供应商！')
		}

		// 选饲料供应商时，带入组织条件
		let FR = []
		if (mustHasOrg.includes(Field)) {
			FR = [{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: state.curOrgId, Right: ")", Logic: "and" }]
		}
		
		if(Field == 'F_QUQY_Feed') {
			FR = [
				{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: state.GYSOrgId, Right: ")", Logic: "and" },
				{ Left: "(", FieldName: "F_QUQY_IsMarket", Compare: "=", Value: state.F_QUQY_IsMarket, Right: ")", Logic: "and" }
				]
		}
		
		let url = `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择&R=1`
		if(FormId === 'BD_MATERIAL'){
			url = `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择&R=1&twice=1`
		}
		uni.navigateTo({
			url,
			success: res => { res.eventChannel.emit('fun', [fun, null, FR, state.materialList]) }
		})

		// 回调方法
		let fun = (list) => {
			if(Field == 'F_QUQY_FeedSupplier'){
				state.F_QUQY_IsMarket = Number(list[0].F_QUQY_IsMarket)
				kdApis.formQuery({
					data: {
						FormId: 'ORG_Organizations',
						FieldKeys: 'FName,FNumber,FOrgID',
						FilterString: [{ "Left": "(", "FieldName": "FName", "Compare": "=", "Value": list[0].FName, "Right": ")", "Logic": "and" }]
					}
				}).then(res=>{
					if(res){
						state.GYSOrgId = res[0].FOrgID
					}
				})
				state.info.Data.Model.F_QUQY_Entity = []
			}
			if (Field == 'F_QUQY_Feed') {
				// 🍕 饲料
				// 🍕 子集里的
				row[Field][FieldSon] = list[0][IdKey]
				row[FieldName] = list[0][IdKeyName]
				// 🍕 查询物料库存单位，不传，后端自动带出
				kdApis.formQuery({
					data: {
						FormId: 'BD_UNIT',
						FieldKeys: 'FName,FNumber,FUNITID',
						FilterString: [{ "Left": "(", "FieldName": "FUNITID", "Compare": "=", "Value": list[0].FStoreUnitID, "Right": ")", "Logic": "and" }]
					}
				}).then(res => {
					if (res && res.length) {
						// row.F_QUQY_ApplyUnitName = res[0].FName
						row.F_QUQY_ApplyUnitName = '袋'
					}
				})
			} else {
				state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
				state.info.Data.Model[FieldName] = list[0][IdKeyName]
				if (BringOther) {
					state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]
				}
			}

			// 🐟 选择养殖批次  0713修改：养殖批次带出组织
			if (Field == 'F_QUQY_BreedingBatch') {
				// 🍕 业务员
				state.info.Data.Model.F_QUQY_SalemanName = list[0]['F_QUQY_Saleman.Fname']
				state.info.Data.Model.F_QUQY_Saleman = {
					FSTAFFNUMBER: list[0].F_QUQY_Saleman
				}
				// 🍕 带出地址
				state.info.Data.Model.F_QUQY_CustAddress = list[0].F_UTPA_Text2
				// 🍕 带出联系电话
				state.info.Data.Model.F_QUQY_Phone = list[0].F_UTPA_Text
				// 🍕 带出组织 0713修改
				state.info.Data.Model.F_QUQY_OrgId = {
					FNumber: list[0]['FUseOrgId.FNumber']
				}
				state.info.Data.Model.F_QUQY_OrgIdName = list[0]['FUseOrgId.FName']
				state.curOrgId = list[0].FUseOrgId
				
				// 🍕 查询养殖批次对应组织的饲料
				kdApis.formQuery({
					data: {
						FormId: 'BD_MATERIAL',
						FieldKeys: 'FName,FNumber,FMaterialGroup,FStoreUnitID,FStockId,FSpecification',
						FilterString: [
							{ "Left": "(", "FieldName": "FDocumentStatus", "Compare": "=", "Value": "C", "Right": ")", "Logic": "and" }, 
							{ "Left": "(", "FieldName": "FForbidStatus", "Compare": "=", "Value": "A", "Right": ")", "Logic": "and" },
							{ "Left": "(", "FieldName": "FMaterialGroup", "Compare": "in", "Value": "101190", "Right": ")", "Logic": "and" },
							{ "Left": "(", "FieldName": "FUseOrgId", "Compare": "=", "Value": list[0].FUseOrgId, "Right": ")", "Logic": "and" },
						]
					}
				}).then(res => {
					if (res && res.length) {
						state.materialList = res
					}
				})

				// 🍕 带出单价
				state.curPrice = list[0].F_QUQY_FeedPrice
				if (state.info.Data.Model.F_QUQY_Entity.length) {
					state.info.Data.Model.F_QUQY_Entity.forEach(it => {
						it.F_QUQY_UnitPrice = list[0].F_QUQY_FeedPrice
						it.F_QUQY_Amount = it.F_RSUS_ApplyQty * list[0].F_QUQY_FeedPrice
					})
				}

				// 🍕 初始化 以组织为前提的字段
				for (let key in state.info.Data.Model) {
					let value = state.info.Data.Model[key]
					if (mustHasOrg.includes(key) && value) {
						if (typeof(value) === 'object') {
							for (let k in value) { value[k] = null }
							state.info.Data.Model[`${key}Name`] = null
							if (state.info.Data.Model[`${key}TEM`]) state.info.Data.Model[`${key}TEM`] = null // 带出的字段
						} else {
							value = null
						}
					}
				}
				// 🍕 初始化 以组织为前提的子集里的字段
				if (state.info.Data.Model.F_QUQY_Entity.length) {
					for (let it of state.info.Data.Model.F_QUQY_Entity) {
						it.F_QUQY_FeedName = null
						it.F_QUQY_Feed = {
							FNUMBER: null
						}
						it.F_QUQY_ApplyUnitName = null
					}
				}
			}
		}
	}

	const appendItem = () => {
		if (state.info.Data.Model.F_QUQY_Entity.length == 0 && !state.info.Data.Model.F_QUQY_BreedingBatchName) return msg('请先选择养殖批次！')
		let obj = {
			F_QUQY_Feed: {
				FNUMBER: null
			},
			F_RSUS_ApplyQty: null,
			F_QUQY_UnitPrice: state.curPrice,
			F_QUQY_Amount: null,
			F_QUQY_ApplyUnitName: null
		}
		state.info.Data.Model.F_QUQY_Entity.push(obj)
	}

	const longpress = (item, index) => {
		let msg = item.F_QUQY_FeedName ? `请确认删除 [ ${item.F_QUQY_FeedName} ] ？` : '请确认删除 ？'
		confirm(msg).then(() => { state.info.Data.Model.F_QUQY_Entity.splice(index, 1) }).catch(() => {})
	}

	const save = async () => {
		await checkForm(state.info.Data.Model, state.rules)
		// 🍕 至少一个子集 && 必填项
		if (state.info.Data.Model.F_QUQY_Entity.length == 0) return msg('请至少选择一种饲料！')
		let flag = true
		let flag2 = true
		state.info.Data.Model.F_QUQY_Entity.forEach((it, i) => {
			if (!it.F_QUQY_FeedName) {
				flag = false
				return msg(`请选择饲料（卡片${i+1}）！`)
			}
			if (!it.F_RSUS_ApplyQty) {
				flag2 = false
				return msg(`请输入申请数量（卡片${i+1}）！`)
			}
		})
		if (!flag || !flag2) return
		state.info.Data.Model.F_QUQY_ReturnOrNot = Number(state.info.Data.Model.F_QUQY_ReturnOrNot)
		kdApis.formSave(state.info).then(res => {
			if (res) {
				msg('保存成功！')
				setTimeout(() => {
					uni.navigateBack()
				}, 300)
			}
		})
	}

	const getDetails = (Id) => {
		kdApis.formView({
			formId: 'QUQY_FeedApplication',
			data: { Id }
		}).then((res) => {
			if (res) {
				let obj = {
					FId: res.Id,
					F_QUQY_OrgId: {
						FNumber: res.F_QUQY_OrgId?.Number
					},
					F_QUQY_Saleman: {
						FSTAFFNUMBER: res.F_QUQY_Saleman?.Number
					},
					F_QUQY_BreedingBatch: {
						FNUMBER: res.F_QUQY_BreedingBatch?.Number
					},
					F_QUQY_ApplyDriver: {
						FNUMBER: res.F_QUQY_ApplyDriver?.Number
					},
					F_QUQY_PullingDriver1: {
						FNUMBER: res.F_QUQY_PullingDriver1?.Number
					},
					F_QUQY_FeedSupplier: {
						FNUMBER: res.F_QUQY_FeedSupplier?.Number
					},
					F_QUQY_Date: moment(res.F_QUQY_Date).format('YYYY-MM-DD'),
					F_QUQY_ApplyDriverName: res.F_QUQY_ApplyDriver?.Name[0].Value,
					F_QUQY_PullingDriver1Name: res.F_QUQY_PullingDriver1?.Name[0].Value,
					F_QUQY_BreedingBatchName: res.F_QUQY_BreedingBatch?.Name[0].Value,
					F_QUQY_SalemanName: res.F_QUQY_Saleman?.Name[0].Value,
					F_QUQY_CustAddress: res.F_QUQY_CustAddress,
					F_QUQY_Phone: res.F_QUQY_Phone,
					F_QUQY_OrgIdName: res.F_QUQY_OrgId?.Name[0].Value,
					F_QUQY_FeedSupplierName: res.F_QUQY_FeedSupplier?.Name[0].Value,
					F_QUQY_Remarks: res.F_QUQY_Remarks,
					F_QUQY_ReturnOrNot: Boolean(Number(res.F_QUQY_ReturnOrNot)),
					F_QUQY_Customer: {
						FNUMBER: res.F_QUQY_Customer?.Number
					},
					F_QUQY_ApplyDriverTEM: res.F_QUQY_ApplyDriver?.F_QUQY_CarNumber,

					F_QUQY_Entity: res.QUQY_t_FeedApplicationE.map(it => {
						return {
							F_QUQY_Feed: {
								FNUMBER: it.F_QUQY_Feed?.Number
							},
							F_QUQY_FeedName: it.F_QUQY_Feed?.Name[0].Value,
							F_QUQY_ApplyUnitName: it.F_QUQY_StoreUnit?.Name[0].Value,
							F_RSUS_ApplyQty: it.F_RSUS_ApplyQty,
							F_QUQY_UnitPrice: it.F_QUQY_UnitPrice,
							F_QUQY_Amount: it.F_QUQY_Amount
						}
					})
				}
				state.curOrgId = res.F_QUQY_OrgId_Id
				Object.assign(state.info.Data.Model, obj)
				state.loading = false
			}
		})
	}

	onLoad(async (query) => {
		if (query.Id) {
			state.pageName = '饲料申请编辑'
			state.userInfo = uni.getStorageSync('userInfo')
			getDetails(query.Id)
		} else {
			// 🍕 申请日期默认当前日期
			state.info.Data.Model.F_QUQY_Date = moment(new Date()).format('YYYY-MM-DD')
			// 🍕 申请司机默认当前司机
			state.userInfo = uni.getStorageSync('userInfo')
			state.info.Data.Model.F_QUQY_ApplyDriver = {
				FNUMBER: state.userInfo?.F_QUQY_Driver?.Number
			}
			state.info.Data.Model.F_QUQY_ApplyDriverName = state.userInfo.F_QUQY_Driver?.Name[0].Value
			// 🍕 拉料司机默认当前司机
			state.info.Data.Model.F_QUQY_PullingDriver1 = {
				FNUMBER: state.userInfo?.F_QUQY_Driver?.Number
			}
			state.info.Data.Model.F_QUQY_PullingDriver1Name = state.userInfo.F_QUQY_Driver?.Name[0].Value
			state.loading = false
		}
	})
</script>
<style lang="scss" scoped>
	.card {
		position: relative;
		width: calc(100% - 60rpx);
		margin: 20rpx auto;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;

		.card-index {
			position: absolute;
			display: flex;
			// align-items: center;
			// justify-content: center;
			width: 40rpx;
			height: 40rpx;
			padding-left: 10rpx;
			font-size: 24rpx;
			background: #409eff;
			color: #fff;
			clip-path: polygon(0 0, 0 40rpx, 10rpx 40rpx, 40rpx 10rpx, 40rpx 0);
		}
	}
</style>
<style lang="scss" scoped>
	::v-deep .van-field {
		border-bottom: 1rpx solid #e9e9ea;
	}
	::v-deep .van-field__label {
		color: #000 !important;
	}
	::v-deep .van-field__control {
		text-align: right;
	}
	::v-deep .van-field__control::-webkit-input-placeholder {
	    color: gray;
	}
	::v-deep.van-field__label {
		&::after {
			margin-left: 2px;
			color: var(--van-field-required-mark-color);
			content: "*";
		}
	}
</style>